#!/bin/bash

################################################################################
# Tonys Director64 - 100% Native Stable Dashboard (v6.0)
# NO PYTHON = NO CRASHES
################################################################################

# 1. Environment Setup
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
if [[ "$SCRIPT_DIR" == *"/Contents/MacOS"* ]]; then
    RESOURCES_DIR="$SCRIPT_DIR/../Resources"
    # Use native AppleScript to find the parent folder of the .app bundle
    # This is more robust against translocation and moving the app
    APP_PARENT_DIR=$(osascript -e 'tell application "Finder" to get POSIX path of (container of (path to me) as alias)' 2>/dev/null | sed 's/\/$//')
    [ -z "$APP_PARENT_DIR" ] && APP_PARENT_DIR="$( cd "$SCRIPT_DIR/../../.." && pwd )"
else
    RESOURCES_DIR="$SCRIPT_DIR"
    APP_PARENT_DIR="$SCRIPT_DIR"
fi
cd "$RESOURCES_DIR"

# Debug Log
DEBUG_LOG="/tmp/director64_debug.log"
echo "--- Launch Debug $(date) ---" > "$DEBUG_LOG"
echo "SCRIPT_DIR: $SCRIPT_DIR" >> "$DEBUG_LOG"
echo "APP_PARENT_DIR: $APP_PARENT_DIR" >> "$DEBUG_LOG"

# Source Homebrew
if [ -f "/opt/homebrew/bin/brew" ]; then eval "$(/opt/homebrew/bin/brew shellenv)"
elif [ -f "/usr/local/bin/brew" ]; then eval "$(/usr/local/bin/brew shellenv)"
fi

export WINEPREFIX="$HOME/.wine"
DATA_DIR="$HOME/.director64_data"
GAME_DIR="$DATA_DIR/game"
mkdir -p "$GAME_DIR"

# Export Portable Wine to PATH if it exists
WINE_DIR="$DATA_DIR/PortableWine"
WINE_BIN=$(find "$WINE_DIR" -name "wine" -type f -path "*/bin/wine" 2>/dev/null | head -n 1)
if [ -f "$WINE_BIN" ]; then
    WINE_ROOT=$(dirname $(dirname "$WINE_BIN"))
    export PATH="$(dirname $WINE_BIN):$PATH"
    export DYLD_FALLBACK_LIBRARY_PATH="$WINE_ROOT/lib"
fi

# 1.5 Robust Installer Logic
install_missing_components() {
    FIX_SCRIPT_PATH="/tmp/director64_installer.sh"
    cat << EOF > "$FIX_SCRIPT_PATH"
#!/bin/bash
clear
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🔧 Tonys Director64 - Official System Installer"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "This utility will install all missing components for you."
echo "Please keep this window open and provide your Mac password if asked."
echo ""

# 1. Homebrew
if ! command -v brew &> /dev/null; then
    echo "📦 [1/5] Installing Homebrew..."
    /bin/bash -c "\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    [ -f "/opt/homebrew/bin/brew" ] && eval "\$(/opt/homebrew/bin/brew shellenv)"
    [ -f "/usr/local/bin/brew" ] && eval "\$(/usr/local/bin/brew shellenv)"
else
    echo "✅ [1/5] Homebrew is already installed."
fi

# 2. Update & Install Core
echo "📦 [2/5] Updating Homebrew..."
brew update

echo "📦 [3/5] Installing FFmpeg & Winetricks..."
brew install ffmpeg winetricks

echo "📦 [3.5/5] Downloading Portable Wine..."
WINE_DIR="$DATA_DIR/PortableWine"
mkdir -p "\$WINE_DIR"
cd "\$WINE_DIR"

echo "🔍 Fetching latest Wine stable release information..."
API_RESPONSE=\$(curl -s https://api.github.com/repos/Gcenx/macOS_Wine_builds/releases)
WINE_URL=\$(echo "\$API_RESPONSE" | grep -o 'https://github.com/Gcenx/macOS_Wine_builds/releases/download/[^"]*/wine-stable-[^"]*.tar.xz' | head -n 1)

if [ -z "\$WINE_URL" ]; then
    WINE_URL="https://github.com/Gcenx/macOS_Wine_builds/releases/download/11.0_1/wine-stable-11.0_1-osx64.tar.xz"
fi
WINE_FILE=\$(basename "\$WINE_URL")

echo "📥 Downloading \$WINE_FILE..."
if curl -L -o "\$WINE_FILE" "\$WINE_URL" --progress-bar; then
    echo "📦 Extracting Wine..."
    tar -xf "\$WINE_FILE"
    rm "\$WINE_FILE"
    echo "✅ Portable Wine downloaded and extracted successfully!"
else
    echo "❌ Wine download failed."
    exit 1
fi

# 3. QuickTime
echo "📦 [4/5] Installing QuickTime 7.2 (Required for Video)..."
export WINEPREFIX="\$HOME/.wine"
WINE_BIN=\$(find "\$WINE_DIR" -name "wine" -type f -path "*/bin/wine" 2>/dev/null | head -n 1)
if [ -n "\$WINE_BIN" ]; then
    WINE_ROOT=\$(dirname \$(dirname "\$WINE_BIN"))
    export PATH="\$(dirname "\$WINE_BIN"):\$PATH"
    export DYLD_FALLBACK_LIBRARY_PATH="\$WINE_ROOT/lib"
    "\$WINE_BIN" wineboot -u 2>/dev/null
    sleep 3
fi
winetricks -q quicktime72

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ ALL COMPONENTS INSTALLED!"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "You can now close this window and restart Tonys Director64."
echo ""
read -p "Press Enter to exit..."
exit
EOF
    chmod +x "$FIX_SCRIPT_PATH"
    open -a Terminal "$FIX_SCRIPT_PATH"
}

# 2. Licensing Logic
get_hwid() { ioreg -d2 -c IOPlatformExpertDevice | awk -F\" '/IOPlatformUUID/{print $(NF-1)}'; }
activate_license() {
    while true; do
        SERIAL_INPUT=$(osascript -e 'display dialog "Please enter your Serial Number to activate:" default answer "" with title "Director64 Verification" buttons {"Quit", "Activate"} default button "Activate" with icon note' 2>/dev/null)
        if echo "$SERIAL_INPUT" | grep -q "Quit"; then exit 0; fi
        SERIAL=$(echo "$SERIAL_INPUT" | sed -n 's/.*text returned:\([^,]*\).*/\1/p' | xargs)
        HWID=$(get_hwid)
        RESPONSE=$(curl -s -k -L -X POST -d "serial_key=$SERIAL&hwid=$HWID" "https://www.director64.com/activate_license.php")
        if [ "$(echo "$RESPONSE" | python3 -c "import sys, json; print(json.load(sys.stdin).get('success', False))" 2>/dev/null)" == "True" ]; then
            echo "$RESPONSE" > "$DATA_DIR/license.json"; break
        else
            MSG=$(echo "$RESPONSE" | python3 -c "import sys, json; print(json.load(sys.stdin).get('message', 'Unknown Error'))" 2>/dev/null)
            osascript -e "display dialog \"Activation Failed:\n$MSG\" buttons {\"Try Again\", \"Quit\"} with icon stop"
        fi
    done
}
[ ! -f "$DATA_DIR/license.json" ] && activate_license

# 3. Main Logic (Native Dashboard)
SIGNAL_FILE="/tmp/director_launch_signal"
rm -f "$SIGNAL_FILE"

# Detect App Translocation (macOS Gatekeeper randomized mount points)
IS_TRANS_L=false
if [[ "$SCRIPT_DIR" == *"/AppTranslocation/"* ]]; then
    IS_TRANS_L=true
fi

# Track the scan directory (defaults to parent folder of the app)
SCAN_DIR="$APP_PARENT_DIR"

# Background Launch Processor
process_launch() {
    local TARGET="$1"
    PROJECTOR=$(find "$GAME_DIR" -iname "projector.exe" -type f 2>/dev/null | head -n 1)
    [ -z "$PROJECTOR" ] && PROJECTOR=$(find "$RESOURCES_DIR" -iname "projector.exe" -type f 2>/dev/null | head -n 1)
    PROJECTOR_DIR="$( cd "$( dirname "$PROJECTOR" )" && pwd )"
    PROJECTOR_NAME="$( basename "$PROJECTOR" )"
    cd "$PROJECTOR_DIR"

    # Locate Wine
    WINE_DIR="$DATA_DIR/PortableWine"
    WINE_BIN=$(find "$WINE_DIR" -name "wine" -type f -path "*/bin/wine" 2>/dev/null | head -n 1)
    if [ -f "$WINE_BIN" ]; then
        WINE_ROOT=$(dirname $(dirname "$WINE_BIN"))
        export PATH="$(dirname $WINE_BIN):$PATH"
        export DYLD_FALLBACK_LIBRARY_PATH="$WINE_ROOT/lib"
        WINE_EXEC="$WINE_BIN"
    else
        WINE_EXEC="wine"
    fi

    if [[ "$TARGET" == "LAUNCH_DEFAULT" ]]; then
        osascript -e "display notification \"Launching Director...\" with title \"Tonys Director64\""
        "$WINE_EXEC" "$PROJECTOR_NAME" &>/dev/null &
    else
        LINK="$PROJECTOR_DIR/launch.dcr"
        cp "$TARGET" "$LINK" 2>/dev/null
        
        # Copy video assets so Projector can find them locally
        for ext in mp4 mov avi qt mpg mpeg m4v wmv swf; do
            find "$(dirname "$TARGET")" -maxdepth 1 -iname "*.$ext" -exec cp -n {} "$PROJECTOR_DIR/" \; 2>/dev/null
        done
        
        pkill -9 wine 2>/dev/null ; sleep 1
        osascript -e "display notification \"Launching: $(basename "$TARGET")\" with title \"Tonys Director64\""
        
        # Run Wine in a subshell and clean up assets ONLY after it exits
        (
            "$WINE_EXEC" "$PROJECTOR_NAME" "launch.dcr" &>/dev/null
            
            # CRITICAL: Clean up to prevent .app bundle bloat
            rm -f "$LINK"
            for ext in mp4 mov avi qt mpg mpeg m4v wmv swf; do
                find "$PROJECTOR_DIR" -maxdepth 1 -iname "*.$ext" -delete 2>/dev/null
            done
        ) &
    fi
}

(
    while true; do
        if [ -f "$SIGNAL_FILE" ]; then
            path=$(cat "$SIGNAL_FILE")
            rm -f "$SIGNAL_FILE"
            process_launch "$path"
        fi
        sleep 1
    done
) &
SIGNAL_WATCHER_PID=$!

# ── Performance Optimization ──────────────────────────────────────────────────
# 1. "Warm Up" Wine Engine in the background
( wineserver -p & ) 2>/dev/null

# 2. Cache System Checks (Runs Once per session)
WINE_DIR="$DATA_DIR/PortableWine"
WINE_BIN=$(find "$WINE_DIR" -name "wine" -type f -path "*/bin/wine" 2>/dev/null | head -n 1)

HB_ST="❌" ; [ -x "$(command -v brew)" ] && HB_ST="✅"
WINE_ST="❌" ; { [ -x "$(command -v wine)" ] || [ -f "$WINE_BIN" ]; } && WINE_ST="✅"
WT_ST="❌" ; [ -x "$(command -v winetricks)" ] && WT_ST="✅"
FF_ST="❌" ; [ -x "$(command -v ffmpeg)" ] && FF_ST="✅"

QT_ST="❌"
WINE_C="$WINEPREFIX/drive_c"
SEARCH_PATHS=( 
    "$WINE_C/windows/system32/qtmlClient.dll" 
    "$WINE_C/windows/syswow64/qtmlClient.dll" 
    "$WINE_C/windows/system32/QuickTime"
    "$WINE_C/Program Files/QuickTime"
    "$WINE_C/Program Files (x86)/QuickTime"
)
for p in "${SEARCH_PATHS[@]}"; do [ -e "$p" ] && QT_ST="✅" && break; done

ANY_MISSING=false
if [[ "$HB_ST" == "❌" || "$WINE_ST" == "❌" || "$WT_ST" == "❌" || "$FF_ST" == "❌" || "$QT_ST" == "❌" ]]; then ANY_MISSING=true; fi
# ──────────────────────────────────────────────────────────────────────────────

while true; do
    # 0. Check for DCRs
    FILES_FOUND=$(find "$SCAN_DIR" -maxdepth 1 -iname "*.dcr" -type f 2>/dev/null | wc -l | tr -d ' ')

    # Use Optimized Cached Status
    STATUS_TXT="Homebrew: $HB_ST | Wine: $WINE_ST | Winetricks: $WT_ST | FFmpeg: $FF_ST | QuickTime: $QT_ST"
    PROMPT_TXT="Tonys Director64 v6.0\n\n$STATUS_TXT\n\nFOLDER: $SCAN_DIR\n\nSELECT ACTION OR FILE:"

    # 3. Build Selection List
    TMPF=$(mktemp /tmp/dcr_list_XXXX.txt)
    find "$SCAN_DIR" -maxdepth 1 -iname "*.dcr" -type f | sort > "$TMPF"
    
    # Start with standard utilities
    AS_LIST="\"[ Launch Director Only ]\", \"─── UTILITIES ───\""
    
    # Add Install Missing at the TOP if something is gone
    if [ "$ANY_MISSING" = true ]; then
        AS_LIST="$AS_LIST, \"[ ⚠️ INSTALL MISSING COMPONENTS ]\""
    fi

    AS_LIST="$AS_LIST, \"[ 📁 Select Another Folder... ]\", \"[ Refresh List ]\", \"[ Tools: Video Converter ]\", \"[ Tools: Uninstall ]\", \"─── Director (DCR) Files ───\""
    
    LABELS=(); PATHS=()
    while IFS= read -r fpath; do
        fn=$(basename "$fpath")
        bytes=$(stat -f%z "$fpath" 2>/dev/null || echo 0)
        size=$(echo "scale=1; $bytes/1048576" | bc 2>/dev/null || echo 0)
        label="◈ $fn ($size MB)"
        LABELS+=("$label"); PATHS+=("$fpath")
        AS_LIST="$AS_LIST, \"$label\""
    done < "$TMPF" ; rm -f "$TMPF"

    PICKED=$(osascript <<APPLESCRIPT
    set theList to { $AS_LIST }
    set picked to choose from list theList \
        with title "Tonys Director64 Dashboard" \
        with prompt "$PROMPT_TXT" \
        OK button name "Select" \
        cancel button name "Quit"
    if picked is false then return "[ Quit Application ]"
    return item 1 of picked
APPLESCRIPT
    )

    # 4. Process Choice
    if [[ "$PICKED" == "[ Quit Application ]" ]]; then
        kill -9 $SIGNAL_WATCHER_PID 2>/dev/null
        exit 0
    fi
    if [[ "$PICKED" == "[ Refresh List ]" || "$PICKED" == "───"* ]]; then continue; fi

    if [[ "$PICKED" == "[ 📁 Select Another Folder... ]" ]]; then
        PICKED_FOLDER=$(osascript -e "try
            return POSIX path of (choose folder with prompt \"Select a folder containing DCR files:\")
        on error
            return \"\"
        end try" 2>/dev/null)
        if [ -n "$PICKED_FOLDER" ]; then SCAN_DIR="$PICKED_FOLDER"; fi
        continue
    fi

    if [[ "$PICKED" == "[ ⚠️ INSTALL MISSING COMPONENTS ]" ]]; then
        install_missing_components
        exit 0
    fi

    if [[ "$PICKED" == "[ Tools: Video Converter ]" ]]; then
        open -a Terminal "$RESOURCES_DIR/Video_Converter.sh" ; exit 0
    elif [[ "$PICKED" == "[ Tools: Uninstall ]" ]]; then
        open -a Terminal "$RESOURCES_DIR/uninstall_everything.sh" ; exit 0
    fi

    # Trigger Launch
    if [[ "$PICKED" == "[ Launch Director Only ]" ]]; then
        process_launch "LAUNCH_DEFAULT"
        kill -9 $SIGNAL_WATCHER_PID 2>/dev/null
        exit 0
    else
        SELECTED_PATH=""
        for i in "${!LABELS[@]}"; do
            if [ "${LABELS[$i]}" = "$PICKED" ]; then SELECTED_PATH="${PATHS[$i]}"; break; fi
        done
        if [ -n "$SELECTED_PATH" ]; then
            process_launch "$SELECTED_PATH"
            kill -9 $SIGNAL_WATCHER_PID 2>/dev/null
            exit 0
        fi
    fi
    
    continue
done

